package rexsee.core.utilities;

import java.util.HashMap;
import java.util.Set;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;

public class RexseeHashMap implements JavascriptInterface {

	public static final String INTERFACE_NAME = "HashMap";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return this;
	}

	private static final String DEFAULT_ID = "default";

	private final Browser mBrowser;
	private final HashMap<String, HashMap<String, String>> mMap;

	public RexseeHashMap(Browser browser) {
		mBrowser = browser;
		mMap = new HashMap<String, HashMap<String, String>>();
	}

	public int sizeIds() {
		return mMap.size();
	}
	public boolean containsId(String id) {
		return mMap.containsKey(id);
	}
	public void removeId(String id) {
		mMap.remove(id);
	}
	public void clearIds() {
		mMap.clear();
	}

	public void add(String key, String value) {
		add(DEFAULT_ID, key, value);
	}
	public void add(String id, String key, String value) {
		if (mMap.containsKey(id)) {
			mMap.get(id).put(key, value);
		} else {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put(key, value);
			mMap.put(id, map);
		}
	}
	public String get(String key) {
		return get(DEFAULT_ID, key);
	}
	public String get(String id, String key) {
		if (mMap.containsKey(id)) {
			String rtn = mMap.get(id).get(key);
			return (rtn == null) ? "" : rtn;
		} else {
			return "";
		}
	}
	public String getKeys() {
		return getKeys(DEFAULT_ID);
	}
	public String getKeys(String id) {
		if (mMap.containsKey(id)) {
			Set<String> keys = mMap.get(id).keySet();
			return Json.toJson(keys);
		} else {
			return "[]";
		}
	}
	public String getJson() {
		return getJson(DEFAULT_ID);
	}
	public String getJson(String id) {
		if (mMap.containsKey(id)) {
			return Json.toJson(mMap.get(id));
		} else {
			return "{}";
		}
	}
	public void remove(String key) {
		remove(DEFAULT_ID, key);
	}
	public void remove(String id, String key) {
		if (mMap.containsKey(id)) {
			mMap.get(id).remove(key);
		}
	}
	public int size() {
		return size(DEFAULT_ID);
	}
	public int size(String id) {
		if (mMap.containsKey(id)) {
			return mMap.get(id).size();
		} else {
			return -1;
		}
	}
	public boolean contains(String key) {
		return contains(DEFAULT_ID, key);
	}
	public boolean contains(String id, String key) {
		if (mMap.containsKey(id)) {
			return mMap.get(id).containsKey(key);
		} else {
			return false;
		}
	}

}
